import { store } from "@/store";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useDictStoreHook } from "@/store/modules/dict";
import router from "@/router";

import AuthAPI, { type LoginData } from "@/api/auth";
import { type UserInfo } from "@/api/system/user";

import { setToken, setRefreshToken, getRefreshToken, clearToken } from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
  const userInfo = useSessionStorage<UserInfo>("userInfo", {} as UserInfo);

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data) => {
          setToken(data?.saTokenInfo?.tokenValue); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          setRefreshToken(data?.saTokenInfo?.tokenValue);
          sessionStorage.setItem("USER_INFO", JSON.stringify(data));
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // function login(loginData: LoginData) {
  //   return new Promise<void>((resolve, reject) => {
  //     AuthAPI.login(loginData)
  //       .then((data) => {
  //         const { tokenType, accessToken, refreshToken } = data;
  //         setToken(tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
  //         setRefreshToken(refreshToken);
  //         resolve();
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // }

  /**
   * 获取用户信息
   *
   * @returns {UserInfo} 用户信息
   */

  interface UserData {
    userId: number;
    username: string;
    nickname: string;
    avatar: string;
    roles: string[];
    perms: string[];
    category: number;
  }

  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      try {
        let getUserInfo = JSON.parse(sessionStorage.getItem("USER_INFO") || "{}");
        console.log(getUserInfo, "getUserInfo");
        let allPerms = [
          "sys:notice:edit",
          "sys:menu:delete",
          "sys:dict:edit",
          "sys:notice:query",
          "sys:dict:delete",
          "sys:config:add",
          "sys:config:refresh",
          "sys:menu:add",
          "sys:user:add",
          "sys:user:export",
          "sys:dept:delete",
          "sys:config:update",
          "sys:user:password:reset",
          "sys:notice:revoke",
          "sys:user:import",
          "sys:dict_type:delete",
          "sys:dict:add",
          "sys:role:add",
          "sys:notice:publish",
          "sys:notice:delete",
          "sys:dept:edit",
          "sys:dict_type:edit",
          "sys:user:query",
          "sys:config:delete",
          "sys:dept:add",
          "sys:notice:add",
          "sys:menu:edit",
          "sys:config:query",
          //新增的
          "sys:master:edit", //新增/修改
          "sys:master:del", //删除
          "sys:master:app", //审核

          "sys:manage:edit", //新增/修改
          "sys:manage:del", //删除
          "sys:manage:app", //审核

          "sys:wareArchives:edit", //新增/修改
          "sys:wareArchives:del", //删除

          "sys:stockOut:edit", //新增/修改
          "sys:stockOut:del", //删除
          "sys:stockOut:app", //审核

          "sys:stockIn:edit", //新增/修改
          "sys:stockIn:del", //删除
          "sys:stockIn:app", //审核

          "sys:planOrderManage:edit", //新增/修改
          "sys:planOrderManage:del", //删除
          "sys:planOrderManage:app", //审核

          "sys:prodOrderManage:edit", //新增/修改

          "sys:user:edit", //新增/修改
          "sys:user:del", //删除
          "sys:user:app", //审核

          "sys:role:edit", //新增/修改
          "sys:role:del", //删除
        ];
        let userData: UserData = {
          userId: getUserInfo.id, // 假设userId为固定值，或者根据需要从userInfo中提取
          username: getUserInfo.account || "", // 用户名从localStorage中获取，默认为空字符串
          nickname: getUserInfo.name || "", // 昵称从localStorage中获取，默认为空字符串
          avatar: "https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif", // 默认头像
          roles: [getUserInfo.account ? getUserInfo.account.toUpperCase() : ""], // 角色为用户名的大写，如果用户名不存在则为空字符串
          perms: getUserInfo.iconList ? getUserInfo.iconList : allPerms, // 权限按钮权限，为了项目不报错，先这样写死
          // perms: allPerms, // 权限按钮权限，为了项目不报错，先这样写死
          category: getUserInfo.category || "",
        };
        console.log(userData, "userData");
        console.log(userInfo.value, "userInfo.value");
        if (userInfo.value && typeof userInfo.value == "object") {
          Object.assign(userInfo.value, { ...userData });
        } else {
          console.error("userInfo.value is not initialized properly");
        }

        resolve(userData);
      } catch (error) {
        console.log(error, "error");
        reject(error);
      }
    });
  }
  // function getUserInfo() {
  //   return new Promise<UserInfo>((resolve, reject) => {
  //     UserAPI.getInfo()
  //       .then((data) => {
  //         if (!data) {
  //           reject("Verification failed, please Login again.");
  //           return;
  //         }
  //         Object.assign(userInfo.value, { ...data });
  //         resolve(data);
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // }

  /**
   * 登出
   */
  function logout() {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.logout()
        .then(() => {
          // 清空用户信息
          sessionStorage.removeItem("USER_INFO");
          sessionStorage.removeItem("userInfo");

          clearUserData();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 刷新 token
   */
  function refreshToken() {
    const refreshToken = getRefreshToken();
    return new Promise<void>((resolve, reject) => {
      AuthAPI.refreshToken(refreshToken)
        .then((data) => {
          const { tokenType, accessToken, refreshToken } = data;
          setToken(tokenType + " " + accessToken);
          setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          console.log(" refreshToken  刷新失败", error);
          reject(error);
        });
    });
  }

  /**
   * 清理用户数据
   *
   * @returns
   */
  function clearUserData() {
    return new Promise<void>((resolve, reject) => {
      try {
        sessionStorage.removeItem("USER_INFO");
        sessionStorage.removeItem("userInfo");

        clearToken();
        usePermissionStoreHook().resetRouter();
        useDictStoreHook().clearDictionaryCache();
        resolve();
      } catch (error) {
        reject(error);
      }
    });
  }

  return {
    userInfo,
    getUserInfo,
    login,
    logout,
    clearUserData,
    refreshToken,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
